<#
.SYNOPSIS
    配置文件
.DESCRIPTION
    无
.NOTES
    无
.LINK
    无
#>


# ============= 导入需要的模块 ===============
$env:LESSCHARSET='utf-8'
# Import-Module oh-my-posh
Import-Module DirColors
Update-DirColors ~/dircolors-solarized/dircolors.ansi-universal
Import-Module posh-git
Import-Module PSReadline
#Set-PoshPrompt PowerLine

# ============= 前置函数 ==============
# 使用cmd下workon(virtualenv)命令
# function SET-WORKON($env_name) {
# 	$env_path = $env:ENV_BASE
#    & $env_path\$env_name\Scripts\activate.ps1
# }

# 2.powershell中执行ll命令
function Get-ChildItemUnix {
    Get-ChildItem $Args[0] |
        Format-Table Mode, @{N='Owner';E={(Get-Acl $_.FullName).Owner}}, Length, LastWriteTime, @{N='Name';E={if($_.Target) {$_.Name+' -> '+$_.Target} else {$_.Name}}}
}

Function Git-Status {
    git status $args
}
Function Git-Log {
    git log --stat --graph $args
}
Function chenv {
    conda deactivate
    conda activate $args[0].toString()
}
Function deenv {
    conda deactivate
}

# 3.powershell中执行head命令
Function Get-Head {
    param(
        [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string]$Path,
        [Parameter(Position = 1)]
        [int]$n = 10
    )

    Get-Content -Path $Path -TotalCount $n
}

# 4.powershell中执行tail命令
Function Get-Tail {
    param(
        [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string]$Path,
        [Parameter(Position = 1)]
        [int]$n = 10
    )

    Get-Content -Path $Path -Tail $n
}


#Set-Alias -Name head -Value Get-Content -First 10
#Set-Alias -Name tail -Value { Get-Content -Tail 10 }
# New-Alias ls lss

# PSReadline的vi模式，不同的光标
function OnViModeChange {
    if ($args[0] -eq 'Command') {
        # Set the cursor to a blinking block.
        Write-Host -NoNewLine "`e[1 q"
    } else {
        # Set the cursor to a blinking line.
        Write-Host -NoNewLine "`e[5 q"
    }
}
#---------------------------------


# ====================== 美化 ========================
# figlet -f 'ANSI Shadow' Hello Mitnick
# oh-my-posh init pwsh --config c:\Users\Mitnick\AppData\Local\oh-my-posh-config\tokyo.omp.json | Invoke-Expression
# oh-my-posh init pwsh --config c:\Users\Mitnick\AppData\Local\Programs\oh-my-posh\themes\avit.omp.json | Invoke-Expression
# oh-my-posh init pwsh --config c:\Users\Mitnick\AppData\Local\oh-my-posh-config\atomicBit.omp.json | Invoke-Expression
# oh-my-posh init pwsh --config c:\Users\Mitnick\AppData\Local\Programs\oh-my-posh\themes\atomicBit.omp.json | Invoke-Expression
$env:VIRTUAL_ENV_DISABLE_PROMPT = 0

#neofetch
#atomic.omp.json
#amro
#cloud-native-azure.omp.json
#easy-term.omp.json

# ========= 下面的代码执行按下ESC后又按下i键的操作 ================
# $shell = New-Object -ComObject Wscript.Shell
# $key = "{ESC}"
# $shell.sendkeys($key)
# $key = "i"
# $shell.sendkeys($key)



#==========
 
#Set-Theme Paradox # 设置主题为 Paradox
 
# =========== PSReadline =================
Set-PSReadLineOption -PredictionSource History # 设置预测文本来源为历史记录
# Set-PSReadLineOption -EditMode Vi           # 初进入时默认在插入模式
 
Set-PSReadLineOption -ViModeIndicator Script -ViModeChangeHandler $Function:OnViModeChange  # 设置vi模式下的光标

Set-PSReadlineKeyHandler -Key Tab -Function Complete # 设置 Tab 键补全
Set-PSReadLineKeyHandler -Key "Ctrl+d" -Function MenuComplete # 设置 Ctrl+d 为菜单补全和 Intellisense
Set-PSReadLineKeyHandler -Key "Ctrl+z" -Function Undo # 设置 Ctrl+z 为撤销
Set-PSReadLineKeyHandler -Key UpArrow -ScriptBlock {
[Microsoft.PowerShell.PSConsoleReadLine]::HistorySearchBackward()
[Microsoft.PowerShell.PSConsoleReadLine]::EndOfLine()
}
Set-PSReadLineKeyHandler -Key DownArrow -ScriptBlock {
[Microsoft.PowerShell.PSConsoleReadLine]::HistorySearchForward()
[Microsoft.PowerShell.PSConsoleReadLine]::EndOfLine()
}
#==========

#设置主题
#Set-PoshPrompt Honukai
#新版的 oh-my-posh 将 Set-Theme 指令修改为了 Set-PoshPrompt 命令
 
#可选主题如下
#Agnoster,Avit,Darkblood,Fish,Honukai,Paradox,PowerLine,robbyrussell,Sorin,tehrob
$env:LF_ICONS="di=📁:\
fi=📃:\Invoke-Expression (&starship init powershell)
tw=🤝:\
ow=📂:\
ln=⛓:\
or=❌:\
ex=🎯:\
*.txt=✍:\
*.mom=✍:\
*.me=✍:\
*.ms=✍:\
*.png=🖼:\
*.webp=🖼:\
*.ico=🖼:\
*.jpg=📸:\
*.jpe=📸:\
*.jpeg=📸:\
*.gif=🖼:\
*.svg=🗺:\
*.tif=🖼:\
*.tiff=🖼:\
*.xcf=🖌:\
*.html=🌎:\
*.xml=📰:\
*.gpg=🔒:\
*.css=🎨:\
*.pdf=📚:\
*.djvu=📚:\
*.epub=📚:\
*.csv=🍍:\
*.xlsx=🍍:\
*.tex=📜:\
*.md=📘:\
*.r=📊:\
*.R=📊:\
*.rmd=📊:\
*.Rmd=📊:\
*.m=📊:\
*.mp3=🎵:\
*.opus=🎵:\
*.ogg=🎵:\
*.m4a=🎵:\
*.flac=🎼:\
*.wav=🎼:\
*.mkv=🎥:\
*.mp4=🎥:\
*.webm=🎥:\
*.mpeg=🎥:\
*.avi=🎥:\
*.mov=🎥:\
*.mpg=🎥:\
*.wmv=🎥:\
*.m4b=🎥:\
*.flv=🎥:\
*.zip=📦:\
*.rar=📦:\
*.7z=📦:\
*.tar.gz=📦:\
*.z64=🎮:\
*.v64=🎮:\
*.n64=🎮:\
*.gba=🎮:\
*.nes=🎮:\
*.gdi=🎮:\
*.1=ℹ:\
*.nfo=ℹ:\
*.info=ℹ:\
*.log=📙:\
*.iso=📀:\
*.img=📀:\
*.bib=🎓:\
*.ged=👪:\
*.part=💔:\
*.torrent=🔽:\
*.jar=♨:\
*.java=♨:\
"


#============= alias =============
Set-Alias -Name make        -Value mingw32-make
Set-Alias -Name lua         -Value lua54

Set-Alias -Name workon      -Value SET-WORKON
Set-Alias -Name grep        -Value findstr
Set-Alias -Name ll          -Value Get-ChildItemUnix
Set-Alias -Name head        -Value Get-Head
Set-Alias -Name tail        -Value Get-Tail

Set-Alias -Name glog        -Value Git-Log
Set-Alias -Name gst         -Value Git-Status
# Set-Alias -Name chenv       -Value Change-CondaEnv
# Set-Alias -Name deenv       -Value Deactivate-CondaEnv

# ============ 变量 =============
$env:LESSCHARSET='utf-8'



## ================= Prompt ================
## 最终显示和Prompt
function Prompt {
    $currentPath = $(Get-Location)
    $username = $env:USERNAME
    $hostname = $env:COMPUTERNAME
    $green = "`e[32m" # ANSI green color
    $cyan = "`e[36m"  # ANSI blue color
    $reset = "`e[0m"  # Reset color

    "$cyan$username@$hostname${reset}:$currentPath$reset>" ## 实际输出的prompt
    
    # $temp=(("$Env:CONDA_PROMPT_MODIFIER".toString()))
    #     Write-Host $temp
    #     Write-Host $temp.trim("() ")
      # Write-Host  ("$Env:CONDA_PROMPT_MODIFIER".toString().trim('(',')'))
      # Write-Host  ("$Env:CONDA_PROMPT_MODIFIER".trim("( )") -split "\\")
    if ($Env:CONDA_PROMPT_MODIFIER) {
        $condaname="$Env:CONDA_PROMPT_MODIFIER".trim("( )") -split "\\"
        $condaname=$condaname[-1]
        Write-Host "(${condaname}) " -NoNewline
    }
    # CondaPromptBackup;
}
function git_branch_internal {
  $dir = $PWD.Path
  do {
    if (Test-Path "${dir}/.git/HEAD") {
      $head = Get-Content "${dir}/.git/HEAD"
      if ($head -eq $Global:GIT_NAME_HEAD) {
        return
      }
      $Global:GIT_NAME_HEAD = $head
      if ($head -match "^ref\:\ refs\/heads\/(?<branch>.*)") {
        $Global:GIT_NAME_TITLE = "branch"
        $Global:GIT_NAME_CONTENT = $Matches.branch
      }
      else {
        $describe = $(git describe --tags --abbrev=7 2> $null)
        if ($describe) {
          $Global:GIT_NAME_TITLE = "tag"
          $Global:GIT_NAME_CONTENT = $describe
        }
        else {
          $Global:GIT_NAME_TITLE = "commit"
          $Global:GIT_NAME_CONTENT = $head.Substring(0, 7)
        }
      }
      $Global:GIT_NAME_LEFT = ":["
      $Global:GIT_NAME_RIGHT = "]"
      "$Global:GIT_NAME_TITLE$Global:GIT_NAME_LEFT$Global:GIT_NAME_CONTENT$Global:GIT_NAME_RIGHT" | Out-Null
      return
    }
    ${dir} = Split-Path -Parent -Path "${dir}"
  } while (${dir})

  $Global:GIT_NAME_TITLE = ""
  $Global:GIT_NAME_CONTENT = ""
  $Global:GIT_NAME_LEFT = ""
  $Global:GIT_NAME_RIGHT = ""
  $Global:GIT_NAME_HEAD = ""
}

function prompt_custom {
  git_branch_internal
  if (${GIT_NAME_TITLE}){
    Write-host "(" -NoNewline
  }
  Write-Host ${GIT_NAME_TITLE}${GIT_NAME_LEFT} -ForegroundColor Cyan -NoNewline
  Write-Host ${GIT_NAME_CONTENT} -ForegroundColor Yellow -NoNewline
  Write-Host ${GIT_NAME_RIGHT} -ForegroundColor Cyan -NoNewline
  # $statusOutput = git status -s 2>$null
  # if ($statusOutput ){
  #     Write-Host "*" -NoNewline
  # }
  if (${GIT_NAME_TITLE}){
    Write-host ")" -NoNewline
  }
  Write-Host $(prompt_bak) -NoNewline
  # Write-Host ">" -NoNewline 
  # Prompt function requires a return, otherwise defaults to factory prompt
  return " "
}

function git_prompt {
  if (Get-Command prompt_bak -errorAction SilentlyContinue) {
    Copy-Item Function::Global:prompt_bak Function::Global:prompt
    Remove-Item Function::prompt_bak
    $Global:GIT_NAME_HEAD = ""; "$Global:GIT_NAME_HEAD" | Out-Null
  }
  else {
    Copy-Item Function::Global:prompt Function::Global:prompt_bak
    Copy-Item Function::Global:prompt_custom Function::Global:prompt
  }
}
git_prompt

## -------------- End Prompt ------------------------



function ssh-copy-id([string] $userAtMachine, $args) {
    $publicKey = "$ENV:USERPROFILE/.ssh/id_rsa.pub"
    if (!(Test-Path "$publicKey")) {
        Write-Error "ERROR: failed to open ID file '$publicKey': No such file"
    } else {
        & cat "$publicKey" | ssh $args $userAtMachine "umask 077; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys || exit 1"
    }
}


#f45873b3-b655-43a6-b217-97c00aa0db58 PowerToys CommandNotFound module

Import-Module -Name Microsoft.WinGet.CommandNotFound
#f45873b3-b655-43a6-b217-97c00aa0db58
